<template>
  <div class="coupon-config-tab">
    <!-- 搜索和操作区域 -->
    <div class="tab-header">
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="站点">
            <el-select v-model="searchForm.siteId" placeholder="全部站点" style="width: 140px;" clearable>
              <el-option 
                v-for="site in sites" 
                :key="site.id" 
                :label="site.name" 
                :value="site.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券">
            <el-select v-model="searchForm.couponId" placeholder="全部优惠券" style="width: 140px;" clearable>
              <el-option 
                v-for="coupon in coupons" 
                :key="coupon.id" 
                :label="coupon.name" 
                :value="coupon.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 120px;" clearable>
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action-area">
        <el-button type="primary" @click="$emit('create', 'add')">
          <el-icon><Plus /></el-icon>
          新增配置
        </el-button>
        <el-button @click="$emit('refresh')">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 配置列表 -->
    <div class="config-list">
      <el-table 
        :data="filteredConfigs" 
        border 
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无配置数据"
      >
        <el-table-column prop="siteName" label="站点" width="120" />
        <el-table-column prop="couponName" label="优惠券" min-width="150" />

        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="showFrequency" label="展示频率" width="120">
          <template #default="scope">
            {{ getFrequencyText(scope.row.showFrequency) }}
          </template>
        </el-table-column>
        <el-table-column prop="userScope" label="用户范围" width="120">
          <template #default="scope">
            {{ getUserScopeText(scope.row.userScope) }}
          </template>
        </el-table-column>

        <el-table-column label="弹窗规则" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.popupRuleId" type="success" size="small">
              {{ getPopupRuleName(scope.row.popupRuleId) }}
            </el-tag>
            <span v-else class="no-rule">未配置</span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="$emit('edit', scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import type { Site, Coupon, SiteCouponConfig, PopupRule } from '@/types/sitePopup'

// Props
interface Props {
  sites: Site[]
  coupons: Coupon[]
  configs: SiteCouponConfig[]
  popupRules: PopupRule[]
  loading: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  refresh: []
  create: ['add' | 'edit']
  edit: [SiteCouponConfig]
  delete: [string]
}>()

// 响应式数据
const searchForm = ref({
  siteId: '',
  couponId: '',
  status: ''
})

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 计算属性
const filteredConfigs = computed(() => {
  let result = [...props.configs]
  
  if (searchForm.value.siteId) {
    result = result.filter(item => item.siteId === searchForm.value.siteId)
  }
  
  if (searchForm.value.couponId) {
    result = result.filter(item => item.couponId === searchForm.value.couponId)
  }
  
  if (searchForm.value.status) {
    result = result.filter(item => item.status === searchForm.value.status)
  }
  
  total.value = result.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 监听配置数据变化
watch(() => props.configs, () => {
  total.value = props.configs.length
  currentPage.value = 1
}, { immediate: true })

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const resetSearch = () => {
  searchForm.value = {
    siteId: '',
    couponId: '',
    status: ''
  }
  currentPage.value = 1
}

const handleDelete = (id: string) => {
  emit('delete', id)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}



const getFrequencyText = (frequency: string) => {
  const frequencyMap: Record<string, string> = {
    'once': '仅一次',
    'every_visit': '每次访问',
    'daily': '每日一次',
    'weekly': '每周一次'
  }
  return frequencyMap[frequency] || frequency
}

const getUserScopeText = (scope: string) => {
  const scopeMap: Record<string, string> = {
    'all': '全部用户',
    'new_user': '新用户',
    'vip_user': 'VIP用户',
    'specific_tags': '指定标签'
  }
  return scopeMap[scope] || scope
}

const getPopupRuleName = (ruleId: string) => {
  const rule = props.popupRules.find(r => r.id === ruleId)
  return rule ? rule.name : ruleId
}
</script>

<style scoped>
.coupon-config-tab {
  padding: 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 20px;
}

.search-area {
  flex: 1;
}

.search-form {
  margin: 0;
}

.action-area {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.config-list {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 12px;
}

.no-rule {
  color: #909399;
  font-size: 12px;
}
</style>
